package servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import dao.UtilisateurDAO;


/**
 * Servlet implementation class CreateUser
 */
@WebServlet("/CreateUser")
public class CreateUser extends HttpServlet {
	private static final long serialVersionUID = 1L;
	public static final String VUE = "/WEB-INF/createUser.jsp";
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public CreateUser() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	    /* Récupération de la session depuis la requête */

	    	this.getServletContext().getRequestDispatcher(VUE).forward( request, response );
	    
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		
		String contextPath = request.getContextPath();
		
		//on recupere les informations utilisateur
		String mail = request.getParameter("emailU");
		String login = request.getParameter("login");
		String mdp = request.getParameter("mdpU");
		
		//on cree un nouvel objet user
		UtilisateurDAO user = new UtilisateurDAO();
		if(user.getUserByLogin(login)==null){
		user.addUser(mail, login, mdp);	
		
		HttpSession session = request.getSession();
		session.setAttribute("user", login);
		
		//recuperation du dernier ID genere
		int idUser = user.getUserByLogin(login).getIdUser();
		String idU = Integer.toString(idUser);
		
		//System.out.println(idU);
		
		// creation d'un cookie
		Cookie cookie = new Cookie("idUser", idU);
		response.addCookie(cookie);

		// on appelle l'autre servlet
		response.sendRedirect(response.encodeRedirectURL(contextPath
				+ "/profilUser"));
		}else{
			request.setAttribute("pseudoNOK", "Pseudo déjà choisi");
			this.getServletContext().getRequestDispatcher(VUE).forward( request, response );
		}
	}

}
